package com.sheliduan.itlearning.blogger.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sheliduan.itlearning.common.aspect.ApiOperationLog;
import com.sheliduan.itlearning.common.domain.dos.ArticleCourseDO;
import com.sheliduan.itlearning.common.domain.dos.OrderDO;
import com.sheliduan.itlearning.common.domain.dos.VideoCourseDO;
import com.sheliduan.itlearning.common.domain.mapper.ArticleCourseMapper;
import com.sheliduan.itlearning.common.domain.mapper.OrderMapper;
import com.sheliduan.itlearning.common.domain.mapper.UserMapper;
import com.sheliduan.itlearning.common.domain.mapper.VideoCourseMapper;
import com.sheliduan.itlearning.common.model.vos.FindOrderPageListReqVO;
import com.sheliduan.itlearning.common.model.vos.FindOrderPageListRspVO;
import com.sheliduan.itlearning.common.utils.PageResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 断舍离
 * @date: 2025/4/17 8:09
 * @description:
 **/
@RestController
@RequestMapping("/blogger")
public class BloggerOrderController {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ArticleCourseMapper articleCourseMapper;

    @Autowired
    private VideoCourseMapper videoCourseMapper;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/order/pageList")
    @ApiOperationLog(description = "订单分页数据获取")
    public PageResponseData findOrderPageList(@RequestBody @Validated FindOrderPageListReqVO reqVO){
        long current = reqVO.getCurrent();
        long size = reqVO.getSize();
        Page<OrderDO> page = new Page<>(current, size);
        Integer bloggerId = reqVO.getUserId();
        // 该博主图文、视频下的所有课程id(去重后)
        Set<Integer> courseIds = new HashSet<>();
        LambdaQueryWrapper<ArticleCourseDO> wrapperArticle = Wrappers.lambdaQuery();
        wrapperArticle.eq(ArticleCourseDO::getUserId, bloggerId);
        for (ArticleCourseDO articleCourseDO : articleCourseMapper.selectList(wrapperArticle)) {
            courseIds.add(articleCourseDO.getId());
        }
        LambdaQueryWrapper<VideoCourseDO> wrapperVideo = Wrappers.lambdaQuery();
        wrapperVideo.eq(VideoCourseDO::getUserId, bloggerId);
        for (VideoCourseDO videoCourseDO : videoCourseMapper.selectList(wrapperVideo)) {
            courseIds.add(videoCourseDO.getId());
        }
        List<Integer> ids = new ArrayList<>(courseIds);
        List<OrderDO> orderDOS = orderMapper.selectList(ids, reqVO.getNumber(), reqVO.getStartDate(), reqVO.getEndDate());
        int total = orderDOS.size();

        // 计算分页起始索引
        int start = (int) ((current - 1) * size);
        // 处理无效页码或越界的情况
        if (current < 1 || start >= total || start < 0) {
            page.setRecords(Collections.emptyList());
        } else {
            int end = Math.min(start + (int) size, total);
            orderDOS = orderDOS.subList(start, end);
            page.setRecords(orderDOS); // 设置当前页数据
        }
        // 设置总记录数（MyBatis-Plus 会自动计算总页数）
        page.setTotal(total);
        List<FindOrderPageListRspVO> vos = new ArrayList<>();
        if(!CollectionUtils.isEmpty(orderDOS)) {
            vos = orderDOS.stream().map(orderDO -> {
                FindOrderPageListRspVO vo = new FindOrderPageListRspVO();
                Integer type = orderDO.getType();
                Integer courseId = orderDO.getCourseId();
                ArticleCourseDO articleCourseDO = articleCourseMapper.selectById(courseId);
                VideoCourseDO videoCourseDO = videoCourseMapper.selectById(courseId);
                String title;
                String cover;
                if(type == 0) {
                    title = articleCourseDO.getTitle();
                    cover = articleCourseDO.getCover();
                }else {
                    title = videoCourseDO.getTitle();
                    cover = videoCourseDO.getCover();
                }
                vo.setId(orderDO.getId());
                vo.setTitle(title);
                vo.setCover(cover);
                vo.setNumber(orderDO.getNumber());
                vo.setPrice(orderDO.getPrice());
                vo.setUsername(userMapper.selectById(orderDO.getUserId()).getUsername());
                vo.setStatus(orderDO.getStatus());
                vo.setOrderTime(orderDO.getOrderTime());
                return vo;
            }).collect(Collectors.toList());
        }
        return PageResponseData.success(page, vos);
    }
}
